import logging
import os
import time
from logging.handlers import RotatingFileHandler
from config.config import config


class Logger:
    def __init__(self, name=__name__):
        # 创建logger
        self.logger = logging.getLogger(name)
        self.logger.setLevel(logging.DEBUG)

        # 确保日志目录存在
        log_dir = os.path.join(config.PROJECT_DIR, 'logs')
        os.makedirs(log_dir, exist_ok=True)

        # 设置日志格式
        log_format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        formatter = logging.Formatter(log_format)

        # 控制台日志处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(logging.INFO)
        console_handler.setFormatter(formatter)

        # 文件日志处理器 (按大小轮转)
        log_file = os.path.join(log_dir, f'{time.strftime("%Y-%m-%d")}.log')
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=1024 * 1024 * 10,  # 10MB
            backupCount=10,
            encoding='utf-8'
        )
        file_handler.setLevel(logging.DEBUG)
        file_handler.setFormatter(formatter)

        # 添加处理器到logger
        self.logger.addHandler(console_handler)
        self.logger.addHandler(file_handler)

    def debug(self, message):
        self.logger.debug(message)

    def info(self, message):
        self.logger.info(message)

    def warning(self, message):
        self.logger.warning(message)

    def error(self, message, exc_info=False):
        self.logger.error(message, exc_info=exc_info)

    def critical(self, message):
        self.logger.critical(message)


# 创建默认logger实例
logger = Logger()


# 使用示例
if __name__ == '__main__':
    logger.debug('这是一条调试信息')
    logger.info('这是一条普通信息')
    logger.warning('这是一条警告信息')
    logger.error('这是一条错误信息')
    logger.critical('这是一条严重错误信息')